package com.yao.ui.fragment

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import com.base.mvp.BaseMvpDialogFragment
import com.yao.AppConfig
import com.yao.R
import com.yao.adapter.IndexAdapter
import com.yao.helper.DialogFragmentHelper
import com.yao.presenter.SearchContract
import com.yao.presenter.SearchPresenter
import com.yao.presenter.bean.IndexDataBean
import com.yao.ui.YaoWebViewActivity
import com.yao.util.AlertUtil
import kotlinx.android.synthetic.main.fragment_search.*
import kotlinx.android.synthetic.main.view_search_head.*

class IndexSearchFragment : BaseMvpDialogFragment<SearchPresenter>(), SearchContract.View {

    var mAdapter: IndexAdapter? = null
    var frather: AppCompatActivity? = null

    companion object {
        const val tag = "search"
        const val STR_KEY = "str_key"

        fun show(fragmentManager: FragmentManager, str: String) {
            val fragment = IndexSearchFragment()
            val bundle = Bundle()
            bundle.putString(STR_KEY, str)
            fragment.arguments = bundle
            DialogFragmentHelper.showDialogFragment(fragmentManager, fragment, tag)
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_search
    }

    override fun isMatchParent(): Boolean {
        return true
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        frather = context as AppCompatActivity
    }

    override fun onDetach() {
        super.onDetach()
        frather = null
    }


    override fun bindViewToPresenter(): SearchPresenter {
        return SearchPresenter()
    }

    override fun initView(p0: Bundle?) {
        mPresenter.attachView(this)
        initColor()
        initWidget()
        initData()
    }

    private fun initColor() {
        dialog?.window?.decorView?.setBackgroundResource(R.drawable.layer_search_bg)
        view?.setPadding(0, getStatusBarHeight(), 0, 0)
    }

    private fun initWidget() {
        val str = arguments?.getString(STR_KEY, "")
        et_search?.setText(str)

        mAdapter = IndexAdapter()
        val mLayoutManager = GridLayoutManager(context, 4, RecyclerView.VERTICAL, false)
        search_rv?.layoutManager = mLayoutManager
        search_rv?.adapter = mAdapter

        mAdapter?.setOnItemClickListener { _, _, position ->
            val indexDataBean = mAdapter?.data?.get(position)
            if (indexDataBean?.itemType == AppConfig.ItemType.ITEMTYPE_INDEX) {
                val item = indexDataBean as IndexDataBean.ChildrenBean
                YaoWebViewActivity.startActivity(context, item.appName, item.appLink)
            }
        }

        iv_search_back?.setOnClickListener {
            dismissAllowingStateLoss()
        }

        et_search?.setOnEditorActionListener(object : TextView.OnEditorActionListener {
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    val s = et_search?.editableText.toString()
                    if (!TextUtils.isEmpty(s)) {
                        mPresenter.getSearchData(s)
                    } else {
                        AlertUtil.t(context, "查询内容不能为空", Toast.LENGTH_SHORT)
                    }
                    // 当按了搜索之后关闭软键盘
                    val manager = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    manager.hideSoftInputFromWindow(et_search.windowToken, 0)
                    return true
                }
                return false
            }
        })
    }

    private fun initData() {
        val str = arguments?.getString(STR_KEY, "")
        if (str != null) {
            mPresenter.getSearchData(str)
        }
    }

    @SuppressLint("PrivateApi")
    private fun getStatusBarHeight(): Int {
        var result = 0
        val resourceId = this.resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = this.resources.getDimensionPixelSize(resourceId)
        }

        if (result == 0) {
            try {
                val c = Class.forName("com.android.internal.R\$dimen")
                val obj = c.newInstance()
                val field = c.getField("status_bar_height")
                val x = Integer.parseInt(field.get(obj).toString())
                result = this.resources.getDimensionPixelSize(x)
            } catch (var7: Exception) {
            }

        }

        if (result == 0) {
            result = Math.ceil((20.0f * this.resources.displayMetrics.density).toDouble()).toInt()
        }

        return result
    }

    override fun onSuccessData(data: List<IndexDataBean.ChildrenBean>) {
        mAdapter?.setNewData(data)
    }

    override fun onFail(code: Int, msg: String) {
        AlertUtil.t(context, msg, Toast.LENGTH_SHORT)
    }

    override fun showLoading() {
        DialogFragmentHelper.showLoadingDialog(fragmentManager)
    }

    override fun hideLoading() {
        DialogFragmentHelper.closeLoadingDialog(fragmentManager)
    }

    override fun onError(p0: Throwable?) {

    }

    override fun release() {

    }
}